from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse, JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import os

# 导入配置和核心模块
from app.config import get_settings
from app.core.logging import setup_logging, get_logger
from app.core.exceptions import AppException

# 导入应用模块
from app.api.endpoints import router
from app.services.scheduler_service import scheduler_service

# 初始化配置和日志
settings = get_settings()
setup_logging()
logger = get_logger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时的初始化操作
    logger.info("应用启动中...")
    logger.info(f"配置信息: 调试模式={settings.debug}, 端口={settings.port}")

    # 启动定时任务服务
    try:
        scheduler_service.start()
        logger.info("定时任务服务启动成功")
    except Exception as e:
        logger.error(f"定时任务服务启动失败: {str(e)}")

    yield

    # 关闭时的清理操作
    logger.info("应用关闭中...")
    try:
        scheduler_service.stop()
        logger.info("定时任务服务已停止")
    except Exception as e:
        logger.error(f"定时任务服务停止失败: {str(e)}")


# 创建FastAPI应用
app = FastAPI(
    title=settings.app_name,
    description="基于AI的智能测试用例生成工具",
    version=settings.app_version,
    debug=settings.debug,
    lifespan=lifespan
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加全局异常处理器


@app.exception_handler(AppException)
async def app_exception_handler(request: Request, exc: AppException):
    """处理应用自定义异常"""
    logger.error(f"应用异常: {exc.message}, 错误码: {exc.error_code}")
    return JSONResponse(
        status_code=400,
        content=exc.to_dict()
    )


@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    """处理通用异常"""
    logger.error(f"未处理的异常: {str(exc)}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={
            "error_code": "INTERNAL_ERROR",
            "message": "服务器内部错误",
            "details": {"error": str(exc)} if settings.debug else {}
        }
    )

# 自定义静态文件处理器，根据配置决定是否禁用缓存


class ConditionalCacheStaticFiles(StaticFiles):
    def __init__(self, *args, **kwargs):
        self.disable_cache = kwargs.pop('disable_cache', False)
        super().__init__(*args, **kwargs)

    def file_response(self, *args, **kwargs):
        response = super().file_response(*args, **kwargs)
        if self.disable_cache:
            response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
            response.headers["Pragma"] = "no-cache"
            response.headers["Expires"] = "0"
        return response


# 挂载静态文件（开发模式禁用缓存）
app.mount("/static", ConditionalCacheStaticFiles(
    directory="app/static",
    disable_cache=settings.debug
), name="static")

# 注册API路由
app.include_router(router, prefix="/api")

# 健康检查端点


@app.get("/health", include_in_schema=False)
async def health_check():
    """健康检查端点"""
    return {"status": "healthy", "version": settings.app_version}

# 根路径重定向到生成用例页面


@app.get("/", include_in_schema=False)
async def root():
    return RedirectResponse(url="/static/generate.html")


if __name__ == "__main__":
    uvicorn.run(
        app,
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        log_level=settings.log_level.lower()
    )
